﻿$(document).ready(function () {

    function BindCategories() {
        var selectedCategoryId = null;

        //if there is a category selected (before this binding)
        if ($("ul#Categories li.selected").length > 0) {
            selectedCategoryId = $("ul#Categories li.selected").tmplItem().data.CategoryId;
        }

        $("ul#Categories li").remove();

        //Invoke AJAX method to get all the categories
        $.post(pathPrefix + "PageLayouts/GetCategoriesList", null, function (result) {
            $("#categoryTemplate").tmpl(result).appendTo("ul#Categories");

            //highlight the specified category by invoking click
            var categoryToSelect = $("ul#Categories li:first");
            if (selectedCategoryId != null) {
                if ($("ul#Categories li[data-category-id=" + selectedCategoryId + "]").length > 0) {
                    categoryToSelect = $("ul#Categories li[data-category-id=" + selectedCategoryId + "]");
                }
            }
            categoryToSelect.click();
        }, "json");
    }

    BindCategories();

    function BindLayouts(categoryId, page) {
        $("ul#Items li").remove();

        $("ul#Items").after("<div class='loadingImage'></div>");

        //Invoke AJAX method to get all the page layouts of specified category
        $.post(pathPrefix + "PageLayouts/GetPageLayoutsList", { "categoryId": categoryId, "Page": page }, function (result) {
            $("#itemTemplate").tmpl(result.Layouts).appendTo("ul#Items");

            //when the image load - fit into container
            $("ul#Items li img").load(function () {
                var container = $(this).parents("li");
                var containerHeight = container.height();
                var containerWidth = container.width();

                var imageHeight = $(this).height();
                var imageWidth = $(this).width();

                if (imageWidth > imageHeight) {
                    $(this).css("width", containerWidth + "px");

                    var offset = (containerHeight - $(this).height()) / 2;
                    offset -= 10;
                    $(container).find(".imageContainer").css("marginTop", offset + "px");
                }
                else {
                    $(this).css("height", containerHeight + "px");

                    var offset = (containerWidth - $(this).width()) / 2;
                    $(container).find(".imageContainer").css("marginRight", offset + "px");
                }

                $(this).show();
            });

            //insert the pages links (if there is more than one)
            if (result.Pages > 1) {
                insertPages(page, result.Pages);
                $("#pagesContainer").show();
            }
            else {
                $("#pagesContainer").hide();
            }

            $("ul#Items").siblings(".loadingImage").remove();

            //define each PageLayout as Draggable element
            $("ul#Items li").draggable({
                revert: "invalid",
                cursorAt: { left: 10, top: 35 },
                handle: ".imageContainer",
                helper: function (event) {
                    //define the image that will be shown while dragging
                    var imageSrc = $(this).find("img").attr("src");
                    var counter = "";

                    var selectedImagesToDrag = $("ul#Items li.selected:not(.ui-draggable-dragging)");

                    //multiple image being dragged
                    if (selectedImagesToDrag.length > 1) {
                        imageSrc = "Content/images/dragImagesIcon.png";
                        counter = "<div>" + selectedImagesToDrag.length + "</div>";
                    }

                    return $("<div id='dragIcon'><img src='" + imageSrc + "' />" + counter + "</div>");
                }
            });

            //define each Category as Droppable element
            $("ul#Categories li").droppable({
                activeClass: "",
                hoverClass: "hover",
                drop: function (event, ui) {
                    //the category id to move the image(s) into
                    var moveToCategoryId = $(this).tmplItem().data.CategoryId;
                    var layoutsIds = "";
                    var selectedImagesToDrag = $("ul#Items li.selected:not(.ui-draggable-dragging)");

                    //check if there are multiple images dragged (or only one)
                    if (selectedImagesToDrag.length <= 1) {
                        layoutsIds = ui.draggable.tmplItem().data.PageLayoutId;
                    }
                    else {
                        layoutsIds = "";
                        selectedImagesToDrag.each(function () {
                            layoutsIds += $(this).tmplItem().data.PageLayoutId + ",";
                        });
                    }

                    var data = { "layoutsIds": layoutsIds, "categoryId": moveToCategoryId };
                    //Invoke AJAX method to change the category of this layout
                    $.post(pathPrefix + "PageLayouts/MoveLayoutsToCategory", data, function () {
                        BindCategories();
                    }, "json");
                }
            });
        }, "json");
    }

    function insertPages(currentPage, pages) {
        $("#pagesContainer").html("<div>עבור לעמוד:</div>");

        //get the number of pages and set link for each of these
        for (var i = 1; i <= pages; i++) {
            //current page
            if (i == currentPage) {
                var page = "<div class='bold'>" + i + "</div>";
            }
            //other page
            else {
                var page = "<a href='' data-page='" + i + "'>" + i + "</a>";
            }
            $("#pagesContainer").append(page);
        }
    }

    //when clicking on a page's link - bind the comments table with this page
    $("#pagesContainer a").live("click", function () {
        var page = $(this).data("page");
        var categoryId = $("ul#Categories li.selected").tmplItem().data.CategoryId;

        BindLayouts(categoryId, page);

        return false;
    });

    $("ul#Categories li").live("click", function () {
        var categoryId = $(this).tmplItem().data.CategoryId;

        //highlight this item
        $(this).siblings(".selected").removeClass("selected");
        $(this).addClass("selected");

        BindLayouts(categoryId, 1);
    });

    $("#btnAddCategory").click(function () {
        var mainDialog = updateDialog("קטגוריה חדשה", "170", "550");

        //Invoke AJAX method to get the Category Form dialog
        $.get(pathPrefix + "PageLayouts/CategoryForm", null, function (result) {
            mainDialog.html(result);
        }, "html");
    });

    $("#frmAddCategory").live("submit", function (e) {
        var data = $(this).serialize();
        $.validator.unobtrusive.parse($(this));

        if ($(this).valid()) {
            var mainDialog = updateDialog("קטגוריה חדשה", "170", "550");

            //Invoke AJAX method to add new category
            $.post(pathPrefix + "PageLayouts/AddCategory", data, function (result) {
                //mainDialog.html(result.Value);
                closeDialog();

                BindCategories();
            }, "json");
        }

        e.preventDefault();
    });

    $("#btnUpdateCategory").click(function () {
        var mainDialog = updateDialog("עדכון קטגוריה", "170", "550");

        var categoryId = $("ul#Categories li.selected").tmplItem().data.CategoryId;

        //Invoke AJAX method to get the Category Form dialog
        $.get(pathPrefix + "PageLayouts/CategoryForm", { "id": categoryId }, function (result) {
            mainDialog.html(result);
        }, "html");
    });

    $("#frmUpdateCategory").live("submit", function (e) {
        var data = $(this).serialize();
        $.validator.unobtrusive.parse($(this));

        if ($(this).valid()) {
            var mainDialog = updateDialog("עדכון קטגוריה", "170", "550");

            //Invoke AJAX method to add new category
            $.post(pathPrefix + "PageLayouts/UpdateCategory", data, function (result) {
                //mainDialog.html(result.Value);
                closeDialog();

                BindCategories();
            }, "json");
        }

        e.preventDefault();
    });

    $(".deleteCategory").live("click", function () {
        var categoryId = $(this).tmplItem().data.CategoryId;

        var mainDialog = updateDialog("מחיקת קטגוריה", "170", "350");

        //Invoke AJAX method to show the delete dialog
        $.get(pathPrefix + "PageLayouts/DeleteCategory", { "id": categoryId }, function (result) {
            mainDialog.html(result);
        }, "html");
    });

    $("#btnConfirmDelete").live("click", function () {
        var categoryId = $(this).parents("#divCategory").data("categoryId");
        var moveToCategoryId = $("#MoveToCategoryId").val();

        var mainDialog = updateDialog("מחיקת קטגוריה", "170", "350");
        var data = { "categoryId": categoryId, "moveToCategoryId": moveToCategoryId };

        //Invoke AJAX method to delete this category
        $.post(pathPrefix + "PageLayouts/DeleteCategory", data, function (result) {
            mainDialog.html(result.Value);

            BindCategories();
        }, "json");
    });

    $("#btnCloseDialog").live("click", function () {
        closeDialog();
    });

    $(".deleteImage").live("click", function () {
        var layoutId = $(this).tmplItem().data.PageLayoutId;

        openConfirmDialog("האם אתה בטוח?", function () {
            //Invoke AJAX method to delete image
            $.post(pathPrefix + "PageLayouts/DeletePageLayout", { "layoutsIds": layoutId }, function (result) {
                BindCategories();
            }, "json");
        });
    });

    $("#btnDeleteMultiple").click(function () {
        var selectedItems = $("ul#Items li.selected:not(.ui-draggable-dragging)");

        if (selectedItems.length > 1) {
            //get the selected images Ids in string array
            var layoutsIds = "";
            selectedItems.each(function () {
                layoutsIds += $(this).tmplItem().data.PageLayoutId + ",";
            });

            openConfirmDialog("האם אתה בטוח שתרצה למחוק את " + selectedItems.length + " הסידורים הנבחרים?", function () {
                //Invoke AJAX method to delete image
                $.post(pathPrefix + "PageLayouts/DeletePageLayout", { "layoutsIds": layoutsIds }, function (result) {
                    BindCategories();
                }, "json");
            });
        }
    });

    //when clicking on an image - highlight it with a specified class
    $("ul#Items li").live("click", function (e) {
        $(this).toggleClass("selected");

        //if the CTRL key is not pressed
        if (e.ctrlKey == false) {
            $(this).siblings("li.selected").removeClass("selected");
        }
    });

    $("#btnSelectAllItems").click(function () {
        //select or deselect all the items
        if ($("ul#Items li").length == $("ul#Items li.selected").length) {
            $("ul#Items li").removeClass("selected");
            $(this).val("בחר הכל");
        }
        else {
            $("ul#Items li").addClass("selected");
            $(this).val("בטל הכל");
        }
    });
});